package com.qys.livesMall.shortVideo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shortVideo.mapper.H2ShortVideoCommentsMapper;
import com.qys.livesMall.shortVideo.mapper.H2ShortVideoMapper;
import com.qys.livesMall.shortVideo.model.dto.app.AppShortVideoCommentQueryDTO;
import com.qys.livesMall.shortVideo.model.dto.app.AppUserCommentDTO;
import com.qys.livesMall.shortVideo.model.dto.sys.SysShortVideoCommentsHideDTO;
import com.qys.livesMall.shortVideo.model.dto.sys.SysShortVideoCommentsPageDTO;
import com.qys.livesMall.shortVideo.model.entity.H2ShortVideo;
import com.qys.livesMall.shortVideo.model.entity.H2ShortVideoComments;
import com.qys.livesMall.shortVideo.model.enums.ShortVideoSourceEnum;
import com.qys.livesMall.shortVideo.model.vo.app.AppShortVideoCommentVO;
import com.qys.livesMall.shortVideo.model.vo.sys.SysShortVideoCommentsVO;
import com.qys.livesMall.shortVideo.service.IH2ShortVideoCommentsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 短视频评论 服务实现类
 * </p>
 *
 * @author dp
 * @since 2023-05-04
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class H2ShortVideoCommentsServiceImpl extends ServiceImpl<H2ShortVideoCommentsMapper, H2ShortVideoComments> implements IH2ShortVideoCommentsService {

    private final H2ShortVideoMapper shortVideoMapper;
    private final H2AppUserMapper userMapper;

    @Override
    public Page<SysShortVideoCommentsVO> pageBySystem(SysShortVideoCommentsPageDTO queryDTO) {
        return baseMapper.pageBySystem(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), queryDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void hideOrShowComments(SysShortVideoCommentsHideDTO commentsHideDTO) {
        List<H2ShortVideoComments> comments = new ArrayList<>(commentsHideDTO.getIds().size());

        commentsHideDTO.getIds().forEach(id -> {
            H2ShortVideoComments videoComments = new H2ShortVideoComments();
            videoComments.setStatus(commentsHideDTO.getStatus());
            videoComments.setId(id);
            comments.add(videoComments);
        });

        updateBatchById(comments);
    }

    @Override
    public String comment(AppUserCommentDTO commentDTO) {

        H2ShortVideo video = shortVideoMapper.selectById(commentDTO.getVideoId());
        if (null == video) {
            throw new QysException(MessageUtils.message("unknown.error"));
        }

        H2ShortVideoComments comments = new H2ShortVideoComments();
        comments.setCreateTime(LocalDateTime.now());
        comments.setShortVideoTitle(video.getTitle());
        comments.setShortVideoContent(commentDTO.getComment());
        comments.setSource(ShortVideoSourceEnum.PLATFORM.getCode());
//        水军评论时 取水军的id和名称
        if(StringUtils.isNotBlank(commentDTO.getUserId())){
            comments.setUserId(commentDTO.getUserId());
            H2AppUser h2AppUser = userMapper.selectById(commentDTO.getUserId());
            if (null != h2AppUser) {
                comments.setAvatar(h2AppUser.getAvatar());
                comments.setUserName(h2AppUser.getUserName());
            }
        }else{
            comments.setUserId(String.valueOf(SecurityUtils.getUserId()));
            comments.setUserName(SecurityUtils.getUsername());
            H2AppUser h2AppUser = userMapper.selectById(SecurityUtils.getUserId());
            if (null != h2AppUser) {
                comments.setAvatar(h2AppUser.getAvatar());
            }
        }
        comments.setShortVideoId(Long.valueOf(commentDTO.getVideoId()));
        if (StringUtils.isNotBlank(commentDTO.getParentId())) {
            comments.setParentId(Long.valueOf(commentDTO.getParentId()));
        }

        baseMapper.insert(comments);

        return comments.getId();
    }

    @Override
    public Page<AppShortVideoCommentVO> pageByApp(AppShortVideoCommentQueryDTO baseQuery) {
        Page<AppShortVideoCommentVO> page = baseMapper.pageByApp(new Page<>(baseQuery.getPageNum(),
                baseQuery.getPageSize()), baseQuery);

        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<AppShortVideoCommentVO> commentVOS = new ArrayList<>(baseQuery.getPageSize());

            //统计信息有多少条回复数据
            for (AppShortVideoCommentVO vo : page.getRecords()) {
                QueryWrapper<H2ShortVideoComments> wrapper = Wrappers.<H2ShortVideoComments>query()
                        .eq("status", 0)
                        .eq("deleted", 0)
                        .eq("parent_id", vo.getId());
                Long count = baseMapper.selectCount(wrapper);
                vo.setCount(count);
                vo.setChildComment(shortVideoMapper.getCommentByParentId(Long.valueOf(vo.getId()), SecurityUtils.getUserId()));
                vo.setAlreadyLiked(baseMapper.haveLiked(Long.valueOf(vo.getId()), SecurityUtils.getUserId()));
                commentVOS.add(vo);
            }
            page.setRecords(commentVOS);
        }

        return page;
    }

    @Override
    @Transactional
    public synchronized int like(String id, byte type) {
        //判断用户是否点赞过
        int had = baseMapper.haveLiked(Long.valueOf(id), SecurityUtils.getUserId());

        //保存主表
        H2ShortVideoComments videoComments = baseMapper.getById(id);
        int num = had > 0 ? videoComments.getLike() - 1 : videoComments.getLike() + 1;
        baseMapper.updateLikeById(videoComments.getId(), num);

        //保存用户点数据
        if(had > 0){
            baseMapper.deleteLike(Long.valueOf(id), SecurityUtils.getUserId());
        } else {
            baseMapper.saveLike(Long.valueOf(id), SecurityUtils.getUserId());
        }
        return num;
    }

    @Override
    public void dislike(String id, byte type) {
        QueryWrapper<H2ShortVideoComments> wrapper = Wrappers.<H2ShortVideoComments>query().eq("id", id)
                .last("for update");
        H2ShortVideoComments videoComments = baseMapper.selectOne(wrapper);
        videoComments.setLike(videoComments.getLike() + ((type == 0) ? 1 : -1));
        baseMapper.updateById(videoComments);
    }

}
